package com.wjc.server.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wjc.server.dto.FileDto;
import com.wjc.server.dto.PageDto;
import com.wjc.server.entity.File;
import com.wjc.server.entity.FileExample;
import com.wjc.server.mapper.FileMapper;
import com.wjc.server.util.CopyUtil;
import com.wjc.server.util.SnowFlake;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
       import java.util.Date;


@Service
public class FileService {
    @Resource
    private FileMapper fileMapper;

    @Resource
    private SnowFlake snowFlake;

    //查询
    public void list(PageDto pageDto){
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        FileExample fileExample = new FileExample();
        List<File> fileList= fileMapper.selectByExample(fileExample);
        PageInfo<File> pageInfo=new PageInfo<>(fileList);
        pageDto.setTotal(pageInfo.getTotal());

        List<FileDto> fileDtosList = CopyUtil.copyList(fileList,FileDto.class);
        pageDto.setList(fileDtosList);

    }

    //保存
    public void save(FileDto fileDto){
        File fileDb=selectByKey(fileDto.getKey());
            Date now =new Date();
        File file=CopyUtil.copy(fileDto,File.class);
        if (ObjectUtils.isEmpty(fileDb)){
            //新增
                file.setCreatedAt(now);
                file.setUpdatedAt(now);
                file.setId(snowFlake.nextId());
                fileMapper.insert(file);
        }else {
            fileDb.setUpdatedAt(now);
            fileDb.setShardIndex(fileDto.getShardIndex());
            fileMapper.updateByPrimaryKey(fileDb);
        }

    }

    public void delete(Long id){
        fileMapper.deleteByPrimaryKey(id);
    }

    public File selectByKey(String key){
        FileExample fileExample=new FileExample();
        fileExample.createCriteria().andKeyEqualTo(key);
        List<File> fileList = fileMapper.selectByExample(fileExample);
        if(CollectionUtils.isEmpty(fileList)){
            return null;
        }else {
            return fileList.get(0);
        }
    }

    public FileDto findByKey(String key){
        return CopyUtil.copy(selectByKey(key),FileDto.class);
    }

}
